package main

import (
	"crypto/sha256"
	"fmt"
	"strings"
)

//计算hash值
func calHash(data []byte) []byte {
	hash := sha256.Sum256(data)
	return hash[:]
}
//创建merkleTree节点
type MerkleNode struct {
	hash []byte
	leftChild *MerkleNode
	rightChild *MerkleNode
}
//创建叶子节点
func NewMerkleLeaf(data []byte) *MerkleNode{
	return &MerkleNode{
		hash:calHash(data),
	}
}
//创建父节点
func NewMerkleParent(left *MerkleNode, right *MerkleNode) *MerkleNode {
	parent := &MerkleNode{
		leftChild: left,
		rightChild: right,
	}

	parent.hash = calHash(append(left.hash,right.hash...))
	return parent
}
//打印节点的哈希值
func (node *MerkleNode) PrintHash() {
	fmt.Printf("Hash: %x\n", node.hash)
}
//切割字符串
func split(data string)[]string{
	return strings.Split(data, " ")
}
//创建叶子节点
func createLeaf(data1 string) []*MerkleNode{
	data := split(data1)
	var leafs []*MerkleNode
	if len(data) % 2 == 1 {
		data = append(data, data[len(data) - 1])
	}
	for _,v := range data{
		leafs = append(leafs, NewMerkleLeaf([]byte(v)))
	}

	return leafs
}
//创建父节点
func createLayer(layer []*MerkleNode) []*MerkleNode{
	var root []*MerkleNode
	count := len(layer)
	if count % 2 == 0 {
		var i = 0
		for {
			if(i <= count/2 - 1 ){
				root = append(root, NewMerkleParent(layer[2*i],layer[2*i+1]))
				i++
			}else {
				break
			}
		}
		return createLayer(root)
	} else {
		root = layer
		return root
	}
}

func main() {
	data := "hehe data 666"
	data1 := createLeaf(data)
	root :=	createLayer(data1)

	////创建叶子结点
	//leaf1 := NewMerkleLeaf([]byte("data1"))
	//leaf2 := NewMerkleLeaf([]byte("data2"))
	//leaf3 := NewMerkleLeaf([]byte("data3"))
	//leaf4 := NewMerkleLeaf([]byte("data4"))

	//创建父节点
	//layer2_left := NewMerkleParent(leaf1,leaf2)
	//layer2_right := NewMerkleParent(leaf3,leaf4)

	//创造更高父节点
	//root := NewMerkleParent(layer2_left,layer2_right)

	//打印根节点的值
	//root.PrintHash()
	root[0].PrintHash()

	/*
	1. 分析项目结构(分析需求)
	2. 将需求抽象成代码结构
	3. 根据需求实现代码
		(1) 创造容器
		(1) 根据功能将容器关联起来


	*/

}